package com.jianyun.jyzs.http;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;


import com.google.gson.Gson;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.activity.CanvasActivity;
import com.jianyun.jyzs.activity.CreateCrmActivity;
import com.jianyun.jyzs.activity.VideoImageGridActivity;
import com.jianyun.jyzs.adapter.CrmAttachmentAdapter;
import com.jianyun.jyzs.bean.AttachmentInfo;
import com.jianyun.jyzs.bean.CrmDetial;
import com.jianyun.jyzs.bean.CrmSearchBean;
import com.jianyun.jyzs.bean.NewCreateCrmBean;
import com.jianyun.jyzs.constant.SysConstant;
import com.jianyun.jyzs.dao.CrmDao;
import com.jianyun.jyzs.utils.CommonUtils;
import com.jianyun.jyzs.utils.FileUtil;
import com.jianyun.jyzs.utils.ImageUtils;
import com.jianyun.jyzs.utils.PathUtil;
import com.jianyun.jyzs.widget.voice.AudioRecorderButton;
import com.jrmf360.rylib.common.util.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.jianyun.jyzs.utils.RceLog;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by liml on 17/8/9.
 */

public class CreateCrmHelper {
    private CreateCrmActivity crmActivity;
    private CrmCreateListener crmCreateListener;
    private int cameraPermissionReqCode = 201;
    private int galleryPermissionReqCode = 202;
    private int filePermissionReqCode = 203;
    private int videoPermissionReqCode = 204;
    public static final int REQUEST_CODE_CAMERA = 11;
    public static final int REQUEST_CODE_GALLERY = 12;
    public static final int REQUEST_CODE_SELECT_FILE = 13;
    public static final int REQUEST_CODE_SELECT_VIDEO = 14;
    public static final int REQUEST_CODE_CANVAS_CAMERA = 10;
    private String userid;
    private String enterpriseCode;
    private String username;
    private final List<AttachmentInfo> attachlist;
    private CrmAttachmentAdapter attachmentAdapter;
    private UploadAttachmentListener uploadAttachmentListener;

    public void setUploadAttachmentListener(UploadAttachmentListener uploadAttachmentListener) {
        this.uploadAttachmentListener = uploadAttachmentListener;
    }

    public List<AttachmentInfo> getAttachlist() {
        return attachlist;
    }

    public interface CrmCreateListener {
        void createSuccess(NewCreateCrmBean newCreateCrmBean);

        void createFail(String msg);
    }

    public CreateCrmHelper(String userid, String username, String enterpriseCode, CrmAttachmentAdapter attachmentAdapter, CreateCrmActivity crmActivity, CrmCreateListener crmCreateListener) {
        this.userid = userid;
        this.username = username;
        this.enterpriseCode = enterpriseCode;
        this.crmActivity = crmActivity;
        this.attachmentAdapter = attachmentAdapter;
        this.crmCreateListener = crmCreateListener;
        attachlist = new ArrayList<>();
    }

    public void createCrm(HashMap<String, String> map, final String userId, final CrmDao crmDao) {
        /*Api api = RetrofitHelper.builderbch().create(Api.class);
        api.createCrm(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<CrmDetial>() {
                    @Override
                    protected void onResponse(CrmDetial response) {
                        Log.i("test", "创建CRM:" + response.toString());
                        RceLog.d("lml", response.toString());
                        if (response.isResult()) {
                            String crmid = response.getPo().getId();
                            //getCrmDetial(crmDao, crmid, userId);

                        } else {
                            crmCreateListener.createFail(response.getMessage());
                        }
                    }

                    @Override
                    protected void onException(String msg) {
                        crmCreateListener.createFail(msg);
                    }
                });*/
    }

    /**
     * 新的创建CRM
     *
     * @param map
     * @param userId
     * @param crmDao
     */
    public void newCreateCrm(HashMap<String, String> map, final String userId, final CrmDao crmDao) {
        Api api = RetrofitHelper.builderErpRoot().create(Api.class);
        api.newCreateCrm(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<NewCreateCrmBean>() {
                    @Override
                    protected void onResponse(NewCreateCrmBean response) {
                        if (response.isResult()) {
                            int crmid = response.getId();
                            //getCrmDetial(crmDao, crmid+"", userId);
                            crmCreateListener. createSuccess(response);
                        } else {
                            crmCreateListener.createFail(response.getMessage());
                        }
                    }

                    @Override
                    protected void onException(String msg) {

                    }
                });
    }

    public void getCrmDetial(final CrmDao dao, String crmid, String userid) {
       /* try {
            Api api = RetrofitHelper.builderbch().create(Api.class);
            api.getCrmDetial(userid, crmid)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new CustomCallback<CrmDetial>() {
                        @Override
                        protected void onResponse(CrmDetial response) {
                            RceLog.d("lml", response.getPo().getName());
                            if (response.isResult()) {
                                dao.insertCrm(response.getPo());
                                //crmCreateListener.createSuccess(response.getPo());
                            } else {
                                crmCreateListener.createFail(response.getMessage());
                            }
                        }

                        @Override
                        protected void onException(String msg) {
                            crmCreateListener.createFail(msg);
                        }
                    });
        } catch (Exception e) {

        }*/

    }

    public void handAttr(LinearLayout llMediaBase) {
        llMediaBase.findViewById(R.id.btn_take_picture).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(crmActivity, Manifest.permission.CAMERA)
                        == PackageManager.PERMISSION_GRANTED) {
                    //有权限
                    if (!CommonUtils.isExitsSdcard()) {
                        Toast.makeText(crmActivity.getApplicationContext(), "拍照需要sdcard支持！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    crmActivity.cameraFile = new File(PathUtil.imagePathName, System.currentTimeMillis() + ".jpg");
                    crmActivity.cameraFile.getParentFile().mkdirs();
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(crmActivity.cameraFile));
                    crmActivity.startActivityForResult(intent, REQUEST_CODE_CAMERA);


                } else {
                    ActivityCompat.requestPermissions(crmActivity,
                            new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
                            cameraPermissionReqCode);
                }
            }
        });
        llMediaBase.findViewById(R.id.btn_picture).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!CommonUtils.isExitsSdcard()) {
                    Toast.makeText(crmActivity.getApplicationContext(), "拍照需要sdcard支持！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (ContextCompat.checkSelfPermission(crmActivity, Manifest.permission.READ_EXTERNAL_STORAGE)
                        == PackageManager.PERMISSION_GRANTED) {

                    try {
                        Intent intent;
                        if (Build.VERSION.SDK_INT < 19) {
                            intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.setType("image/*");
                        } else {
                            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        }
                        crmActivity.startActivityForResult(intent, REQUEST_CODE_GALLERY);
                    } catch (Exception e) {
                    }

                } else {
                    ActivityCompat.requestPermissions(crmActivity,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                            galleryPermissionReqCode);
                }
            }
        });
        final AudioRecorderButton btnVoice = (AudioRecorderButton) llMediaBase.findViewById(R.id.btn_voice);
        btnVoice.setAudioFinishRecorderListener(new AudioRecorderButton.AudioFinishRecorderListener() {
            @Override
            public void onFinish(float seconds, String filePath) {
                if (!(new File(filePath).exists())) {
                    return;
                }
                AttachmentInfo info = new AttachmentInfo();
                info.setType(SysConstant.VOICE);
                info.setPath(filePath);
                info.setFilename(FileUtil.getFileName(filePath));
                info.setDuration((int) seconds);
                notifyAttachment(info);
            }
        });

        llMediaBase.findViewById(R.id.btn_video).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!CommonUtils.isExitsSdcard()) {
                    Toast.makeText(crmActivity, "视频需要sdcard支持！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (ContextCompat.checkSelfPermission(crmActivity, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(crmActivity, VideoImageGridActivity.class);
                    crmActivity.startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
                } else {
                    ActivityCompat.requestPermissions(crmActivity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, videoPermissionReqCode);
                }

            }
        });
        llMediaBase.findViewById(R.id.btn_file).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtil.showNoWaitToast(crmActivity, "打开文件选择器");
//                crmActivity.startActivityForResult(new Intent(crmActivity,FileExplorerTabActivity.class),REQUEST_CODE_SELECT_FILE);
            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        RceLog.d("lml", "Helper___onActivityResult");
        if (resultCode == -1) {
            if (requestCode == REQUEST_CODE_CAMERA) {
                if (crmActivity.cameraFile != null && crmActivity.cameraFile.length() > 0) {
                    Intent intent = new Intent(crmActivity, CanvasActivity.class);
                    intent.putExtra("imgPath", ImageUtils.getScaledImage(crmActivity.cameraFile.getAbsolutePath()));
                    crmActivity.startActivityForResult(intent, REQUEST_CODE_CANVAS_CAMERA);
                } else {
                    if (crmActivity.cameraFile != null && crmActivity.cameraFile.exists()) {
                        crmActivity.cameraFile.delete();
                    }
                }
            } else if (requestCode == REQUEST_CODE_CANVAS_CAMERA & data != null) {
                final String imgPath = data.getStringExtra("filePath");
                if (imgPath != null && imgPath.length() > 0) {
                    AttachmentInfo info = new AttachmentInfo();
                    info.setType(SysConstant.IMAGE);
                    info.setPath(imgPath);
                    info.setFilename(FileUtil.getFileName(imgPath));
                    notifyAttachment(info);
                }
            } else if (requestCode == REQUEST_CODE_SELECT_VIDEO & data != null) {
                int length = data.getIntExtra("dur", 0);
                String filePath = data.getStringExtra("path");
                AttachmentInfo info = new AttachmentInfo();
                info.setType(SysConstant.VIDEO);
                info.setDuration(length);
                info.setPath(filePath);
                info.setFilename(FileUtil.getFileName(filePath));
                notifyAttachment(info);
            } else if (requestCode == REQUEST_CODE_GALLERY & data != null) {
                Uri selectedImage = data.getData();
                Cursor cursor = crmActivity.getContentResolver().query(selectedImage, null, null, null, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex("_data");
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    cursor = null;

                    if (picturePath == null || picturePath.equals("null")) {
                        Toast toast = Toast.makeText(crmActivity, "找不到图片", Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        return;
                    }
                    try {
                        Intent intent = new Intent(crmActivity, CanvasActivity.class);
                        RceLog.d("lml", "picturePath");
                        intent.putExtra("imgPath", ImageUtils.getScaledImage(picturePath));
                        crmActivity.startActivityForResult(intent, REQUEST_CODE_CANVAS_CAMERA);
                    } catch (Exception e) {
                    }
                } else {
                    File file = new File(selectedImage.getPath());
                    if (!file.exists()) {
                        Toast toast = Toast.makeText(crmActivity, "找不到图片", Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        return;

                    }
                    Intent intent = new Intent(crmActivity, CanvasActivity.class);
                    intent.putExtra("imgPath", ImageUtils.getScaledImage(file.getAbsolutePath()));
                    crmActivity.startActivityForResult(intent, REQUEST_CODE_CANVAS_CAMERA);
                }
            } else if (requestCode == REQUEST_CODE_SELECT_FILE & data != null) {
                String filePath = data.getStringExtra(SysConstant.msg_key_string1);
                if (filePath == null) {
                    Toast.makeText(crmActivity, "文件不存在", Toast.LENGTH_SHORT).show();
                    return;
                }
                File file = new File(filePath);
                if (file == null || !file.exists()) {
                    Toast.makeText(crmActivity, "文件不存在", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (file.length() > Integer.valueOf(crmActivity.getString(R.string.fileSize)) * 1024 * 1024) {
                    Toast.makeText(crmActivity, "文件不能大于" + crmActivity.getString(R.string.fileSize) + "M", Toast.LENGTH_SHORT).show();
                    return;
                }
                RceLog.d("lml", "filePath=" + filePath);
                AttachmentInfo info = new AttachmentInfo();
                info.setFilename(FileUtil.getFileName(filePath));
                info.setPath(filePath);
                info.setType(SysConstant.FILE);
                notifyAttachment(info);
            }
        }
    }

    private void notifyAttachment(AttachmentInfo info) {
        attachlist.add(info);
        attachmentAdapter.setAttachlist(attachlist);
    }

    private int number = 0;

    public interface UploadAttachmentListener {
        void uploadCount(int count);
    }

    public void uploadAttachment(List<AttachmentInfo> attachlist, CrmDetial.CrmDetailBean po) {
        number = attachlist.size();
        String folderName = po.getFolderName();
        String crmid = po.getId();
        for (AttachmentInfo att : attachlist) {

            switch (att.getType()) {
                case SysConstant.IMAGE:
                    //uploadImage(crmid, att);
                    break;
                case SysConstant.VOICE:
                    //uploadVoice(crmid, att);
                    break;
                case SysConstant.VIDEO:
                    //uploadVideo(crmid, att);
                    break;
                case SysConstant.FILE:
                    uploadFile(folderName, att);
                    break;
            }
        }

    }

    private void uploadVideo(String crmid, AttachmentInfo info) {
        /*try {


            Api api = RetrofitHelper.builderbch().create(Api.class);
            HashMap<String, RequestBody> map = new HashMap<>();
            map.put("enterpriseCode", RequestBody.create(MediaType.parse("text/plain"), enterpriseCode));
            map.put("userId", RequestBody.create(MediaType.parse("text/plain"), userid));
            map.put("crmId", RequestBody.create(MediaType.parse("text/plain"), crmid));
            map.put("duration", RequestBody.create(MediaType.parse("text/plain"), info.getDuration() + ""));
            map.put("fileExtName", RequestBody.create(MediaType.parse("text/plain"), "mp4"));
            File file = new File(info.getPath());
            FileRequestBody fileRequestBody = new FileRequestBody(file, null);
            MultipartBody.Part formData = MultipartBody.Part.createFormData("file", info.getFilename(), fileRequestBody);
            api.uploadCrmVideo(map, formData)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new Subscriber<Object>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            number -= 1;
                            uploadAttachmentListener.uploadCount(number);
                        }

                        @Override
                        public void onNext(Object o) {
                            RceLog.d("lml", o.toString());
                            number -= 1;
                            uploadAttachmentListener.uploadCount(number);

                        }
                    });
        } catch (Exception e) {

        }*/
    }

    private void uploadVoice(String crmid, AttachmentInfo info) {
//        try {
//
//
//            Api api = RetrofitHelper.builderbch().create(Api.class);
//            HashMap<String, RequestBody> map = new HashMap<>();
//            map.put("enterpriseCode", RequestBody.create(MediaType.parse("text/plain"), enterpriseCode));
//            map.put("userId", RequestBody.create(MediaType.parse("text/plain"), userid));
//            map.put("crmId", RequestBody.create(MediaType.parse("text/plain"), crmid));
//            map.put("duration", RequestBody.create(MediaType.parse("text/plain"), info.getDuration() + ""));
//            map.put("fileExtName", RequestBody.create(MediaType.parse("text/plain"), "mp3"));
//            File file = new File(info.getPath());
//            FileRequestBody fileRequestBody = new FileRequestBody(file, null);
//            MultipartBody.Part formData = MultipartBody.Part.createFormData("file", info.getFilename(), fileRequestBody);
//            api.uploadCrmVoice(map, formData)
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribeOn(Schedulers.io())
//                    .subscribe(new Subscriber<Object>() {
//                        @Override
//                        public void onCompleted() {
//
//                        }
//
//                        @Override
//                        public void onError(Throwable e) {
//                            e.printStackTrace();
//                            number -= 1;
//                            uploadAttachmentListener.uploadCount(number);
//                        }
//
//                        @Override
//                        public void onNext(Object o) {
//                            RceLog.d("lml", o.toString());
//                            number -= 1;
//                            uploadAttachmentListener.uploadCount(number);
//                        }
//                    });
//        } catch (Exception e) {
//
//        }
    }

    private void uploadImage(String crmid, AttachmentInfo info) {
//        try {
//            Api api = RetrofitHelper.builderbch().create(Api.class);
//            HashMap<String, RequestBody> map = new HashMap<>();
//            map.put("enterpriseCode", RequestBody.create(MediaType.parse("text/plain"), enterpriseCode));
//            map.put("userId", RequestBody.create(MediaType.parse("text/plain"), userid));
//            map.put("crmId", RequestBody.create(MediaType.parse("text/plain"), crmid));
//            map.put("fileExtName", RequestBody.create(MediaType.parse("text/plain"), "jpg"));
//            File file = new File(info.getPath());
//            FileRequestBody fileRequestBody = new FileRequestBody(file, null);
//            MultipartBody.Part formData = MultipartBody.Part.createFormData("file", info.getFilename(), fileRequestBody);
//            api.uploadCrmImage(map, formData)
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribeOn(Schedulers.io())
//                    .subscribe(new Subscriber<Object>() {
//                        @Override
//                        public void onCompleted() {
//
//                        }
//
//                        @Override
//                        public void onError(Throwable e) {
//                            e.printStackTrace();
//                            number -= 1;
//                            uploadAttachmentListener.uploadCount(number);
//                        }
//
//                        @Override
//                        public void onNext(Object o) {
//                            RceLog.d("lml", o.toString());
//                            number -= 1;
//                            uploadAttachmentListener.uploadCount(number);
//
//                        }
//                    });
//        } catch (Exception e) {
//
//        }
    }

    private void uploadFile(String floadername, AttachmentInfo info) {
        Api api = RetrofitHelper.builderErpRoot().create(Api.class);
        HashMap<String, RequestBody> map = new HashMap<>();
        map.put("enterpriseCode", RequestBody.create(MediaType.parse("text/plain"), enterpriseCode));
        map.put("FolderID", RequestBody.create(MediaType.parse("text/plain"), floadername));
        map.put("FolderName", RequestBody.create(MediaType.parse("text/plain"), CrmDetial.CrmDetailBean.class.getSimpleName()));
        map.put("BusinessClass", RequestBody.create(MediaType.parse("text/plain"), "CRM"));
        map.put("employeeId", RequestBody.create(MediaType.parse("text/plain"), userid));
        map.put("employeeName", RequestBody.create(MediaType.parse("text/plain"), username));
        map.put("FileName", RequestBody.create(MediaType.parse("text/plain"), info.getFilename()));
        File file = new File(info.getPath());
        FileRequestBody fileRequestBody = new FileRequestBody(file, null);
        MultipartBody.Part formData = MultipartBody.Part.createFormData("filedata", info.getFilename(), fileRequestBody);
        api.uploadFile(map, formData)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        number -= 1;
                        uploadAttachmentListener.uploadCount(number);
                    }

                    @Override
                    public void onNext(Object o) {
                        RceLog.d("lml", o.toString());
                        number -= 1;
                        uploadAttachmentListener.uploadCount(number);

                    }
                });
    }
}
